<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY 杭州博也网络科技有限公司
// |-----------------------------------------------------------------------------------
// | Author: 青 <99701759@qq.com>
// | Copyright (c) 2013-2016, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------
// 微信用户表中的信息在$this->userinfo
// 用户newmember表的信息在$this->newmember中
// 用户角色表的信息在$this->role中
namespace Home\Controller;
use Admin\Api\NewmemberApi;
use Admin\Api\PostApi;
use Admin\Api\RoleApi;
use Admin\Api\SuitApi;
use Bbs\Api\BbsMemberApi;
use Shop\Api\BannersApi;
use Shop\Api\ProductMemberPriceApi;
use Think\Controller;

use Shop\Api\ProductApi;
use Shop\Api\ProductFaqApi;
use Shop\Api\ProductGroupApi;
use Shop\Api\ProductSkuApi;
use Tool\Api\OrdersApi;
use Weixin\Api\WxuserApi;
use Shop\Api\AddressApi;
use Shop\Api\ProductImageApi;
use Shop\Api\FavoritesApi;
class CustomizationController extends HomeController {

    /*
     * 定制商品确认页
     * */
    public function index(){
        $map['uid'] = $this->userinfo['id'];
        $map['product_id'] = I('product_id');
        $postmap['id'] = 2;
        $postinfo = apiCall(PostApi::GET_INFO,array($postmap));

        if($postinfo['status']){
            $this->assign('post_content',htmlspecialchars_decode($postinfo['info']['post_content']));
        }

        $suitres = apiCall(SuitApi::GET_INFO,array($map));

        if($suitres['status']){

            if(($suitres['info']['create_time'] + 3600*24*30*12) > time()){
                //跳转到定制商品购买页面
                $this->redirect('Customization/detail', array('id' => 144), '0', '页面跳转中...');
            }else{
                $this->display();
            }
        }else{
            //进行定制商品的确认
            $this->display();
        }
    }


    /*
     * 定制商品
     * */
    public function sure(){
        //查询储值余额是否够
        $map['wx_id'] = $this->userinfo['id'];
        $ninfo = apiCall(NewmemberApi::GET_INFO,array($map));

        if($ninfo['status']){
            if($ninfo['info']['store_money'] >= 5000){
                $modal = M();
                $modal->startTrans();
                $flag = false;

                $add = array(
                    'uid'=>$this->userinfo['id'],
                    'product_id'=>I('product_id'),
                    'money'=>'5000',
                    'create_time'=>time()
                );

                $addsuit = apiCall(SuitApi::ADD,array($add));

                if(!$addsuit['status']){
                    $flag = true;
                }

                $nowmoney = $ninfo['info']['store_money']-5000;
                $nsave = array(
                    'store_money'=>$nowmoney
                );

                $ssave = apiCall(NewmemberApi::SAVE,array($map,$nsave));

                if(!$ssave['status']){
                    $flag = true;
                }

                if($flag){
                    $modal->rollback();
                    $this->error('参加私人定制失败');
                }else{
                    $modal->commit();
                    $this->success('参加私人定制成功');
                }

            }else{
                $this->error('抱歉你的储值而不够');
            }
        }

    }


    /*
     * 私人定制商品详情页面
     * */
    public function detail()
    {
        $id = I('id');
        $uid = UID;
        $result = apiCall(ProductApi::DETAIL, array($id));

        if ($result['status']) {

            //清除不用字段
            unset($result['info']['uid']);
            unset($result['info']['loc_country']);
            unset($result['info']['loc_province']);
            unset($result['info']['loc_city']);
            unset($result['info']['loc_address']);
            unset($result['info']['createtime']);
            unset($result['info']['updatetime']);
            unset($result['info']['onshelf']);
            unset($result['info']['status']);
            unset($result['info']['weight']);
            unset($result['info']['synopsis']);
            unset($result['info']['dt_origin_country']);
            unset($result['info']['_price']);
            unset($result['info']['dt_goods_unit']);
            unset($result['info']['pid']);
            $result['info']['detail'] = htmlspecialchars_decode($result['info']['detail']);
            $has_sku = apiCall(ProductSkuApi::HAS_SKU, array($id));

            if ($has_sku['status']) {
                //0为统一规格,1为多规格
                $has_sku = $has_sku['info'];
            } else {
                $this->ajaxReturn($has_sku['info']);
            }
            $result['info']['has_sku'] = $has_sku;

            if ($has_sku == 1) {
                //多规格传值
                //规格id
                $skuId = apiCall(ProductSkuApi::GET_SKU_ID, array($id, 'sku_id'));
                if ($skuId['status']) {
                    $result['info']['sku_id'] = json_decode($skuId['info'], true);
                } else {
                    $this->ajaxReturn($skuId['info']);
                }
                //规格名称
                $skuName = apiCall(ProductSkuApi::GET_SKU_NAME, array($id, 'sku_desc'));
                if ($skuName['status']) {
                    $result['info']['sku_name'] = json_decode($skuName['info'], true);

                } else {
                    $this->ajaxReturn($skuName['info']);
                }
                //规格详细信息
                $skulist = apiCall(ProductSkuApi::QUERY_NO_PAGING, array(array('product_id' => $id)));
                $min_price = 1e18;
                $max_price = 0.0;
                if ($skulist['status']) {

                    foreach ($skulist['info'] as $k => $vo) {
                        $map['sku_id'] = $vo['id'];
                        $vo['price'] = ceil($vo['price'] * $this->role['discount']);
                        /*
                         * 还需要一个会员等级进行限制操作
                         * */
                        $member_price = apiCall(ProductMemberPriceApi::GET_INFO, array($map));
                        if ($member_price['status']) {
                            $skulist['info'][$k]['member_group_id'] = $member_price['info']['price'];
                        }

                        if ($vo['price'] < $min_price) {
                            $min_price = $vo['price'];
                        }
                        if ($vo['price'] > $max_price) {
                            $max_price = $vo['price'];
                        }
                    }
                    $result['info']['sku_list'] = $skulist['info'];
                    $result['info']['min_price'] = $min_price;

                    $result['info']['max_price'] = $max_price;

                } else {
                    $this->ajaxReturn($skulist['info']);
                }

            } else {
                $skulist = apiCall(ProductSkuApi::GET_INFO, array(array('product_id' => $id)));
                if ($skulist['status']) {
                    unset($skulist['info']['sku_id']);
                    unset($skulist['info']['sku_desc']);
                    unset($skulist['info']['createtime']);
                    unset($skulist['info']['icon_url']);
                    $result['info']['sku_info'] = $skulist['info'];
                    $result['info']['min_ori_price'] = $skulist['info']['ori_price'];
                    $result['info']['min_price'] = $skulist['info']['price'];
                } else {
                    $this->ajaxReturn($skulist['info']);
                }
            }

            $group = apiCall(ProductGroupApi::GET_GROUP_BY_ID, array($id));
            if (!$group['status']) {
                $this->ajaxReturn($group['info']);
            }
            $result['info']['group'] = $group['info'];

            $result['info']['favorite'] = 0;
            if ($uid != 0) {
                $map = array(
                    'favorite_id' => $id,
                    'uid' => $uid,
                );
                $favorite = apiCall(FavoritesApi::COUNT, array($map));
                if ($favorite['status']) {
                    if ($favorite['info'] > 0) {
                        $result['info']['favorite'] = 1;
                    }
                } else {
                    $this->ajaxReturn($favorite['info']);
                }
            }

            if (is_null($result['info']['group'])) {
                unset($result['info']['group']);
            }

            //处理图片
            $result['info']['main_img'] = getImageUrl($result['info']['main_img']);
            if (is_array($result['info']['imgs'])) {
                foreach ($result['info']['imgs'] as $k => $v) {
                    $result['info']['imgs'][$k] = getImageUrl($v);
                }
            }
            if ($has_sku == 1 && is_array($result['info']['sku_list'])) {
                foreach ($result['info']['sku_list'] as $k => $v) {
                    $result['info']['sku_list'][$k]['icon_url'] = getImageUrl($v['icon_url']);
                }
            }

            $all_quantity = 0;
            //处理一下总库存的问题
            foreach ($result['info']['sku_list'] as $k => $v) {
                $all_quantity = $all_quantity + $v['quantity'];
            }
            $result['info']['all_quantity'] = $all_quantity;
            $this->assign($result['info']);

            //查询相应的用户的购买情况
            $this->display();
        }
    }


    /*
     * 下单
     * */
    public function checkout(){
        session('pid',I('pid'));
        session('count',I('count'));
        session('sku_id',I('sku_id'));

        //收货地址的判断
        $addremap['uid'] = $this->userinfo['id'];

        //判断是否有可供选择的地址没有就需要新建
        $hasaddrres = apiCall(AddressApi::COUNT , array($addremap));
        if($hasaddrres['status']){
            $this->assign('addrecount',$hasaddrres['info']);
        }
        //判断是否进行地址选择如果选择了就用选择的 没有选择用默认的
        $addressmap['id'] = empty(I('addressid')) ? $this->userinfo['default_address'] : I('addressid');

        $selectres = apiCall(AddressApi::GET_INFO , array($addressmap));
        if($selectres['status']){

            $this->assign($selectres['info']);
            session('addressid',$selectres['info']['id']);//为的是在生成订单时获得相应的地址信息的方便
            $this->assign('addressid',$selectres['info']['id']);
        }


        $pid = !empty(I('pid')) ? I('pid') : session('pid');
        $count = !empty(I('count')) ? I('count') : session('count');
        $sku_id = !empty(I('sku_id')) ? I('sku_id'):session('sku_id');

        $this->assign('pid',$pid);
        $this->assign('count',$count);
        //判断一下商品数量
        $quantity = apiCall(ProductSkuApi::GET_INFO,array(array('sku_id' => $sku_id,'product_id' => $pid)));
        if($quantity['status']){
            if($quantity['info']['quantity'] < $count){
                $this->error('对不起库存不足');
            }
            $this->assign('skuid',$quantity['info']['id']);
            $this->assign('sku_desc',$quantity['info']['sku_desc']);
            $price['price'] = $quantity['info']['price']*$this->role['discount'];
            $price['totalprice'] = $quantity['info']['price']*$this->role['discount']*$count;
            $this->assign('price',$price);
        }
        $pinfores = apiCall(ProductApi::GET_INFO,array(array('id'=>$pid)));
        if($pinfores['status']){
            $this->assign('info',$pinfores['info']);
        }

        //获取商品图片
        $main_img_type = 6015;

        $result = apiCall(ProductImageApi::QUERY_NO_PAGING,array(array('pid' => $pid)));

        if(!$result['status']){
            return $result;
        }
        $main_img = "";
        foreach($result['info'] as $vo){
            if($vo['type'] == $main_img_type){
                $main_img = $vo['img_id'];
            }
        }
        $this->assign('img',$main_img);


        //查询收货地址
        $map=array(
            'uid'=> '1',
        );

        $result=apiCall(AddressApi::QUERY_NO_PAGING,array($map," id desc "));
        if($result['status']){
            if(empty($result['info'])){
                $result['info'] = array();
            }
            $this->assign('address',$result['info']);
        }
        //储值
        $this->assign('store_money',$this->newmember['store_money']);
        //总定金
        $suitmap = array(
            'product_id'=>$pid,
            'uid'=>$this->userinfo['id'],
        );
        $suitres = apiCall(SuitApi::GET_INFO,array($suitmap));
        if($suitres['status']){
            $this->assign('suit_money',$suitres['info']['money']);
        }
        $this->display();
    }


    /*
     * 生成订单
     * */
    public function produce_order(){
        session('pid',null);
        session('count',null);
        session('sku_id',null);
        session('idnum',null);

        //购买人的用户ID
        $uid = $this->userinfo['id'];
        $idskuidnum = I("idskuidnum","");


        $arr = explode('###',$idskuidnum);
        $pid = $arr['0'];
        $skuid = $arr['1'];
        $num = $arr['2'];


        $address_id = I('addressid'); //收货地址ID
        $note = I('note');

        //有购物车会出现多个物品一起提交

        $pay_type = 2; //支付类型 1:支付宝

        //1. 收货地址
        if(empty($address_id)){
            $this->error('收货地址缺失');
        }
        $result = apiCall(AddressApi::GET_INFO,array(array('id'=>$address_id)));
        if($result['status']){
            if(is_null($result['info'])){
                $this->error('收货地址缺失');
            }
        }else{
            $this->error('收货地址缺失');
        }

        $address = $result['info'];
        unset($address['id']);

        $entity = array();

        //合并收货地址
        $entity = array_merge($entity,$address);

        //2. 购物车信息
        $map = array(
            'id'=>$skuid,
        );
        //1. 本商城生成的支付编号
        $result = apiCall(ProductSkuApi::GET_INFO,array($map));

        if($result['status']){

            $total = $result['info']['price'];

            $items = array();

            $pmap['id'] = $pid;
            $productinfo = apiCall(ProductApi::GET_INFO,array($pmap));
            if($productinfo['status']){
                $name = $productinfo['info']['name'];
                $weight = $productinfo['info']['weight'];
                $imgmap['pid'] = $pid;
                $imgmap['type'] = '6015';
                $imgid = apiCall(ProductImageApi::GET_INFO,array($imgmap));

                if($imgid['status']){
                    $img = $imgid['info']['img_id'];
                    $tmp = array(
                        'p_id' => $pid,
                        'name' => $name,
                        'ori_price' => $result['info']['ori_price'],
                        'price' => $result['info']['price'],
                        'icon_url' => $img,
                        'count' => $num,
                        'sku_id' => $skuid,
                        'sku_desc' => $result['info']['sku_desc'],
                        'createtime' => time(),
                        'dt_origin_country' => $productinfo['info']['dt_origin_country'],
                        'weight' => $weight,
                        'taxrate' => '0',
                    );
                    $items[] = $tmp;
                }
            }


            $model = M();
            $model->startTrans();
            $flag = false;
            $balance = I('chuzhi','0');

            if($total < $balance){
                $balance = $total;
                //增加一个标志用于判断是否是全积分和储值
                $bflag = true;
            }

            if($balance != 0){
                $suitmap =array(
                    'uid'=>$this->userinfo['id'],
                    'product_id'=>$pid,
                );

                $suitinfo = apiCall(SuitApi::GET_INFO,array($suitmap));

                if($suitinfo['status']){
                    //判断储值是否大于顾客提交的
                    if($suitinfo['info']['money'] < $balance){
                        $this->error('你的定金没有这么多了');
                    }
                }

                $suitsave['money'] = $suitinfo['info']['money'] - $balance;

                $suitres = apiCall(SuitApi::SAVE,array($suitmap,$suitsave));
                if(!$suitres['status']){
                    $flag = true;
                }

            }


            $order = array(
                'uid' => $entity['uid'],
                'order_code' => getOrderid($uid),
                'price' => $total,
                'post_price' => '0',
                'note' => $note,
                'pay_status'=>$bflag ? 1 : 0,
                'comment_status'=>0,
                'storeid' => '0',
                'idcode'=> '0',
                'discount_money'=> '0',
                'from'=> '1',
                'tax_amount'=> '0',
                'goods_amount'=> $total,
                'pay_type'=> '2',
                'pay_balance'=>$balance,
                'pay_score'=> '0',
                'items' => $items
            );

            $entity = array_merge($entity,$order);

            $result = apiCall(\Shop\Api\OrdersApi::ADD_ORDER,array($entity));

            if($result['status']){

                //订单生成成功后库存的减少
                $quantitymap = array(
                    'id' => $skuid
                );
                $findquantity = apiCall(ProductSkuApi::GET_INFO,array($quantitymap));
                if($findquantity['status']){
                    $saveq['quantity'] = $findquantity['info']['quantity']- $num;
                    $saveres = apiCall(ProductSkuApi::SAVE,array($quantitymap,$saveq));
                    if(!$saveres['status']){
                        $flag = true;
                    }
                }else{
                    $flag = true;
                }

            }else{
                $flag = false;
            }

            if($flag){
                $model->rollback();
                $this->error('对不起 订单生成出现问题');
            }else{

                $model->commit();
                if($bflag){
                    $this->success('下单成功',U('Order/wait_order',array('status'=>0)));
                    die();
                }
                $this->success('订单生成成功',U('TestPay/jsapi',array('order_code'=>$order['order_code'])));
            }

        }else{
            $this->error('对不起 订单生成出现问题');
        }

    }



}